package com.xujie.controller;

import com.xujie.common.response.Result;
import com.xujie.controller.dto.WeatherDailyResponse;
import com.xujie.domain.service.WeatherDailyService;
import com.xujie.infra.entity.WeatherDaily;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Xujie
 * @since 2024/12/21 12:41
 **/

@Slf4j
@RestController
@RequestMapping("/api/weather")
public class WeatherController {

  @Autowired
  private WeatherDailyService weatherDailyService;

  /**
   * 获取指定城市近7天的天气数据
   * 
   * @param city 城市名称，默认为"上海"
   * @return 天气数据列表
   */
  @GetMapping("/last7days")
  public Result<List<WeatherDailyResponse>> getLast7DaysWeather(@RequestParam(defaultValue = "上海",name = "city") String city) {
    try {
      log.info("获取{}近7天天气数据", city);

      // 获取天气数据
      List<WeatherDaily> weatherDailyList = weatherDailyService.getLast7DaysWeather(city);

      // 转换为响应DTO
      List<WeatherDailyResponse> responseList = weatherDailyList.stream()
          .map(daily -> {
            WeatherDailyResponse response = new WeatherDailyResponse();
            BeanUtils.copyProperties(daily, response);
            return response;
          })
          .collect(Collectors.toList());

      return Result.success(responseList);
    } catch (Exception e) {
      log.error("获取天气数据失败", e);
      return Result.error("获取天气数据失败：" + e.getMessage());
    }
  }
}
